package com.cmw.auntapp.core.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.widget.ImageButton;
import android.widget.ImageView;

import androidx.core.content.ContextCompat;

import com.cmw.auntapp.R;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.security.PublicKey;

/**
 * @desc: Android Bitmap最全基本操作：与Drawable 、File、btye[]互转
 * @author: chengmingwei
 * @date: 2021/5/14 7:30 AM
 * @contact: phone(微信同号):13922111489 / email: 340360491@qq.com
 */
public class BitmapUtil {
    private static BitmapUtil btimapUtil;
    private Context context;

    private BitmapUtil(Context context) {
        this.context = context;
    }

    public static BitmapUtil getBtimapUtil(Context context) {
        if (btimapUtil == null) {
            synchronized (BitmapUtil.class) {
                btimapUtil = new BitmapUtil(context);
            }
        }
        return btimapUtil;
    }

    /**
     * 加载网络图片
     * @param imageButton ImageButton 对象
     * @param url   网络图片地址URL
     */
    public void setDrawableByNetWork(ImageButton imageButton, String url) {
        new Thread(()->{
            Drawable drawable = loadImageFromNetwork(url);
            // post() 特别关键，就是到UI主线程去更新图片
            imageButton.post(() -> imageButton.setImageDrawable(drawable)) ;
        }).start();
    }

    /**
     * 加载网络图片
     * @param imageView ImageView 对象
     * @param url   网络图片地址URL
     */
    public void setDrawableByNetWork(ImageView imageView, String url) {
        new Thread(()->{
            Drawable drawable = loadImageFromNetwork(url);
            // post() 特别关键，就是到UI主线程去更新图片
            imageView.post(() -> imageView.setImageDrawable(drawable)) ;
        }).start();
    }


    private Drawable loadImageFromNetwork(String imageUrl)
    {
        Drawable drawable = null;
        try {
            // 可以在这里通过文件名来判断，是否本地有此图片
            drawable = Drawable.createFromStream(
                    new URL(imageUrl).openStream(), "image.jpg");
        } catch (IOException e) {
            Log.d("test", e.getMessage());
        }
        if (drawable == null) {
            Log.d("test", "null drawable");
        } else {
            Log.d("test", "not null drawable");
        }

        return drawable ;
    }

    /**
     * 根据drawable 资源ID获取 Drawable 对象
     *
     * @param resId 资源ID
     * @return  返回 Drawable 对象
     */
    public Drawable getDrawable(int resId) {
       return ContextCompat.getDrawable(context, resId);
    }

    /**
     * 文件转Bitmap
     */
    public Bitmap fileToBitmap(String filePath) {
        File file = new File(filePath);
        BitmapFactory.Options options = new BitmapFactory.Options();
        /**
         *压缩长宽各为一半避免图片过大装载不了
         */
        options.inPurgeable = true;
        options.inSampleSize = 2;
        return BitmapFactory.decodeFile(filePath, options);
    }

    /**
     * Bitmap转文件
     */
    public File bitmapToFile(Bitmap bitmap, String saveFilePath) {
        File file = new File(saveFilePath);//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
            return file;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 数组转Bitmap
     */
    public Bitmap btyesToBtimap(byte[] bytes) {
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    /**
     * Btimap转数组
     */
    public byte[] btimapToBtyes(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * Bitmap转Drawable
     */
    public Drawable btimapToDrawable(Bitmap bitmap) {
        return new BitmapDrawable(context.getResources(), bitmap);
    }

    /**
     * Drawable转Bitmap
     */
    public Bitmap drawableToBitmap(Drawable drawable) {
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();
        // 取 drawable 的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        //建立对应 bitmap 的画布
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        // 把 drawable 内容画到画布中
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * 带圆角的绘制转Bitmap
     */
    public Bitmap creatRoundedBitmap(Bitmap bitmap, float roundPx) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Bitmap output = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, w, h);
        final RectF rectF = new RectF(rect);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }

    /**
     * 带倒影的绘制Bitmap
     */
    public Bitmap createReflectionBitmap(Bitmap bitmap) {
        final int reflectionGap = 4;
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        /**
         * 获取矩阵变换
         * */
        Matrix matrix = new Matrix();
        matrix.preScale(1, -1);
        Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, h / 2, w, h / 2, matrix, false);
        Bitmap bitmapWithReflection = Bitmap.createBitmap(w, (h + h / 2), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmapWithReflection);
        canvas.drawBitmap(bitmap, 0, 0, null);
        Paint deafalutPaint = new Paint();
        canvas.drawRect(0, h, w, h + reflectionGap, deafalutPaint);
        canvas.drawBitmap(reflectionImage, 0, h + reflectionGap, null);
        Paint paint = new Paint();
        LinearGradient shader = new LinearGradient(0, bitmap.getHeight(),
                0, bitmapWithReflection.getHeight() + reflectionGap,
                0x70ffffff, 0x00ffffff, Shader.TileMode.CLAMP);
        paint.setShader(shader);
        // Set the Transfer mode to be porter duff and destination in
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        // Draw a rectangle using the paint with our linear gradient
        canvas.drawRect(0, h, w, bitmapWithReflection.getHeight() + reflectionGap, paint);
        return bitmapWithReflection;
    }
}
